<template>
  <div class="layer" ref="layer"></div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import * as THREE from 'three'
import EarthImg from '@/assets/images/earth.png'

const scene = new THREE.Scene()
const renderer = new THREE.WebGLRenderer({
  antialias: true
})

export default defineComponent({
  name: 'SceneTravel',
  data () {
    return {
      scene: new THREE.Scene()
    }
  },
  mounted () {
    const plane = localStorage.getItem('_plane_')
    plane ? this.initPlane() : this.initGeome()
  },
  methods: {
    initGeome () {
      const geometry = new THREE.BoxGeometry(1, 1, 1)
      const camera = this.initGetCamera()
      const material = new THREE.MeshBasicMaterial({
        color: 0x00ff00
      })
      const mesh = new THREE.Mesh(geometry, material)
      scene.add(mesh)
      camera.position.z = 5

      function animate () {
        requestAnimationFrame(animate)
        mesh.rotation.x += 0.01
        mesh.rotation.y += 0.01
        renderer.render(scene, camera)
      }
      animate()
    },
    initPlane () {
      // const geometry = new THREE.PlaneGeometry(5, 5) // 默认在XOY平面上
      const geometry = new (THREE as any).PlaneBufferGeometry(5, 5)
      const camera = this.initGetCamera()
      const textureLoader = new THREE.TextureLoader()

      textureLoader.load(EarthImg, (texture) => {
        const material = new THREE.MeshBasicMaterial({
          color: 0xffff00,
          map: texture,
          // transparent: true,
          opacity: 0.8,
          side: THREE.DoubleSide
        })
        camera.position.z = 5
        scene.add(new THREE.Mesh(geometry, material))

        renderer.render(scene, camera)
      })
    },
    initGetCamera () {
      const layer = this.$refs.layer as HTMLElement
      const { clientWidth, clientHeight } = layer
      renderer.setSize(clientWidth, clientHeight)
      // renderer.setClearColor(0x00ff00)
      layer.appendChild(renderer.domElement)
      return new THREE.PerspectiveCamera(75, clientWidth / clientHeight, 0.1, 1000)
    }
  }
})
</script>

<style scoped lang="scss">
.layer {
  display: flex;
  width: 640px;
  height: 480px;
}
</style>
